import '@/styles/global.scss';
import '@/lib/config';
import '@/lib/highlight';
import type { ReactNode } from 'react';
import Wrapper from '@/app/[locale]/wrapper';
import { jetBrainsMonoFont, ralewayFont } from '@/lib/font';
import { getMetadata } from '@/lib/tool';
import classNames from 'classnames';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from '@/lib/dictionaries';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { queryPath } from '@/services/api';
import type { IPath } from '@/interfaces';
import Navbar from '@/app/[locale]/navbar/navbar';
import Footer from '@/app/[locale]/footer/footer';
import DefaultMetadata from '@/lib/metadata';

const raleway = ralewayFont;
const jetBrainsMono = jetBrainsMonoFont;

export const metadata = getMetadata();

async function getData() {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });

    const responses = await Promise.all([req1]);
    const resp1 = await ((await responses[0]) as Response).json();

    return {
      isSuccess: true,
      path: resp1.data as IPath,
    };
  } catch (e) {
    return {
      isSuccess: false,
    };
  }
}

export default async function RootLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: { locale: string; navbar?: string; footer?: string; class?: string };
}) {
  const data = await getData();
  const { locale: _locale, messages } = await getMessages(params.locale);
  const metadata = new DefaultMetadata('page', ['/paths', '/'], data.path);
  const clientPage = messages.clientPage;

  return (
    <html lang={_locale} data-bs-theme="auto">
      <body
        className={classNames(
          raleway.className,
          raleway.variable,
          jetBrainsMono.variable,
          params.class ?? 'yw-bg row mx-0',
        )}
      >
        <NextIntlClientProvider locale={_locale} messages={{ clientPage }}>
          <Wrapper metadata={metadata.toString()}>
            <>
              {data.isSuccess && params.navbar !== 'false' && (
                <Navbar
                  source={{
                    path: data.path!,
                  }}
                  locale={_locale}
                />
              )}
              {children}
              {params.footer !== 'false' && (
                <Footer
                  source={{
                    path: data.path!,
                  }}
                  locale={_locale}
                />
              )}
            </>
          </Wrapper>
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

export const dynamic = 'force-dynamic';
